import { createElementWithClass } from "./Api.js";

export const createPost = (postData) => {
    const postWrapper = createElementWithClass('div', 'post-container');
    // 封面部分
    const postCoverWrapper = createElementWithClass('div', 'post-cover-container');
    const postCover = createElementWithClass('img', 'post-cover');
    postCover.src = postData.cover;
    postCoverWrapper.appendChild(postCover);
    postWrapper.appendChild(postCoverWrapper);

    // 作品信息Wrapper
    const postInfoWrapper = createElementWithClass('div', 'post-info-container');
    // 用户信息
    // 头像
    const postAvator = createElementWithClass('img', 'avator');
    postAvator.src = postData.avatar;
    postInfoWrapper.appendChild(postAvator);
    // 用户名与标签
    const postUserInfo = createElementWithClass('span', "post-userinfo");
    // 用户名
    const postUsername = createElementWithClass('div', 'post-username');
    postUsername.innerHTML = postData.name;
    postUserInfo.appendChild(postUsername);
    // 类别标签
    const postBadge = createElementWithClass('div', 'post-badge');
    const badgeText= postData.badge.toUpperCase();
    if(badgeText !== "") {
        postBadge.innerHTML = badgeText;
        postUserInfo.appendChild(postBadge);
    }
    postInfoWrapper.appendChild(postUserInfo);

    const postStats = createElementWithClass('span', 'post-stats');
    // 点赞
    const postLikes = createElementWithClass('span', 'post-like-container post-stat-item');
    const likeIcon = createElementWithClass('img', 'like-icon icon');
    likeIcon.src = './imgs/icon-like.svg';
    postLikes.appendChild(likeIcon);
    const likeNum = createElementWithClass('span', 'num-text');
    likeNum.innerHTML = postData.likes;
    postLikes.appendChild(likeNum);
    postStats.appendChild(postLikes);
    // 观看
    const postViews = createElementWithClass('span', 'post-view-container post-stat-item');
    const viewIcon = createElementWithClass('img', 'view-icon icon');
    viewIcon.src = './imgs/icon-view.svg';
    postViews.appendChild(viewIcon);
    const viewNum = createElementWithClass('span', 'num-text');
    viewNum.innerHTML = postData.views;
    postViews.appendChild(viewNum);
    postStats.appendChild(postViews);
    postInfoWrapper.appendChild(postStats);
    postWrapper.appendChild(postInfoWrapper);

    return postWrapper;
}

export const createPosts = () => {
    const postsContainer = createElementWithClass('section', 'all-posts-container')
    fetch('./task.json')
    .then((res) => res.json())
    .then((res) => {
        console.log(res);
        if(res !== null) {
            for(let item of res) {
                const postItem = createPost(item);
                postsContainer.appendChild(postItem);
            }
        }
    })
    .catch((err) => {
        console.log("获取Posts失败：",err);
    })
    return postsContainer;
}